const bcrypt = require('bcryptjs')
const { Users } = require('../../model/user')
module.exports = async(req, res) => {
    const { email, password } = req.body
    if (email.trim().length == 0 || password.trim().length == 0) {
        res.render('./admin/error', {
            msg: '邮箱或密码错误'
        })
    }
    const user = await Users.findOne({ email })
    if (user) {
        let isEqual = await bcrypt.compare(password, user.password);
        if (isEqual) {
            req.session.username = user.username;
            req.session.role = user.role
            req.app.locals.userInfo = user; //设置全局模板使用数据
            if (user.role == 'admin') {
                res.redirect('/admin/user') //重定向
            } else {
                res.redirect('/home/index') //重定向

            }
        } else {
            res.status(400).render('./admin/error', {
                msg: '邮箱或密码错误'
            })
        }
    } else {
        res.status(400).render('./admin/error', {
            msg: '邮箱或密码错误'
        })
    }

}